"""
项目服务
提供项目数据的数据库操作功能
"""

from typing import Optional, Dict, Any, List
from sqlalchemy.orm import Session
from sqlalchemy.exc import SQLAlchemyError
from datetime import datetime
from src.models.project import Project
from src.utils.logging import get_logger

logger = get_logger(__name__)


class ProjectService:
    """项目服务类"""

    def __init__(self, db_session: Session):
        self.db = db_session

    def create_project(self, name: str, description: Optional[str] = None, state: Optional[Dict[str, Any]] = None) -> Optional[Project]:
        """
        创建新项目
        
        Args:
            name: 项目名称
            description: 项目描述
            state: 项目初始状态
            
        Returns:
            Project: 创建的项目对象，如果失败则返回None
        """
        try:
            project = Project(
                name=name,
                description=description,
                state=state
            )
            self.db.add(project)
            self.db.commit()
            self.db.refresh(project)
            logger.info(f"项目创建成功: {name} (ID: {project.id})")
            return project
        except SQLAlchemyError as e:
            self.db.rollback()
            logger.error(f"创建项目失败: {str(e)}")
            return None

    def get_project(self, project_id: str) -> Optional[Project]:
        """
        获取项目信息
        
        Args:
            project_id: 项目ID
            
        Returns:
            Project: 项目对象，如果不存在则返回None
        """
        try:
            return self.db.query(Project).filter(Project.id == project_id).first()
        except SQLAlchemyError as e:
            logger.error(f"获取项目失败: {str(e)}")
            return None

    def get_all_projects(self) -> List[Project]:
        """
        获取所有项目列表
        
        Returns:
            List[Project]: 项目列表
        """
        try:
            return self.db.query(Project).all()
        except SQLAlchemyError as e:
            logger.error(f"获取项目列表失败: {str(e)}")
            return []

    def update_project_state(self, project_id: str, state: Dict[str, Any]) -> bool:
        """
        更新项目状态
        
        Args:
            project_id: 项目ID
            state: 新的项目状态
            
        Returns:
            bool: 更新成功返回True，否则返回False
        """
        try:
            project = self.db.query(Project).filter(Project.id == project_id).first()
            if project:
                project.state = state  # type: ignore
                project.updated_at = datetime.utcnow()  # type: ignore
                self.db.commit()
                logger.info(f"项目状态更新成功: {project_id}")
                return True
            return False
        except SQLAlchemyError as e:
            self.db.rollback()
            logger.error(f"更新项目状态失败: {str(e)}")
            return False

    def update_project(self, project_id: str, name: Optional[str] = None, 
                      description: Optional[str] = None) -> bool:
        """
        更新项目信息
        
        Args:
            project_id: 项目ID
            name: 新的项目名称（可选）
            description: 新的项目描述（可选）
            
        Returns:
            bool: 更新成功返回True，否则返回False
        """
        try:
            project = self.db.query(Project).filter(Project.id == project_id).first()
            if project:
                if name is not None:
                    project.name = name  # type: ignore
                if description is not None:
                    project.description = description  # type: ignore
                project.updated_at = datetime.utcnow()  # type: ignore
                self.db.commit()
                logger.info(f"项目信息更新成功: {project_id}")
                return True
            return False
        except SQLAlchemyError as e:
            self.db.rollback()
            logger.error(f"更新项目信息失败: {str(e)}")
            return False

    def delete_project(self, project_id: str) -> bool:
        """
        删除项目
        
        Args:
            project_id: 项目ID
            
        Returns:
            bool: 删除成功返回True，否则返回False
        """
        try:
            project = self.db.query(Project).filter(Project.id == project_id).first()
            if project:
                self.db.delete(project)
                self.db.commit()
                logger.info(f"项目删除成功: {project_id}")
                return True
            return False
        except SQLAlchemyError as e:
            self.db.rollback()
            logger.error(f"删除项目失败: {str(e)}")
            return False


# 导出
__all__ = ["ProjectService", "Project"]